package com.dollkey.hdownload.serv;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;


import com.dollkey.hdownload.R;
import com.dollkey.hdownload.util.HRxBus;
import com.dollkey.hdownload.util.StringUtils;
import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.PRDownloader;

import java.io.File;
import java.text.DecimalFormat;


// 用于处理时刻签到金币奖励的服务
public class DownLoadNormalService extends IntentService {

    public static final String TAG = "DownLoadNormalService";

    public static final String ACTION_DLE_START = "com.dollkey.hdownload.DownLoadNormalService.action.ACTION_DLE_START";
    public static final String ACTION_DLE_SUCCESS = "com.dollkey.hdownload.DownLoadNormalService.action.ACTION_DLE_SUCCESS";

    public static final String PARAM_APK_URL = "apk";
    public static final String PARAM_APK_NAME = "name";
    private NotificationManager mNotificationManager;
    private Notification.Builder mBuilder;
    private Context mContext;
    public static final String id = "channel_1";
    public static final String name = "channel_name_1";
    private int mId;

    public DownLoadNormalService() {
        super("DownLoadNormalService");
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(),
                PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(false);
            channel.enableVibration(false);
            channel.setVibrationPattern(new long[]{0});
            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
            mBuilder = new Notification.Builder(getApplicationContext(), id)
                    .setContentTitle("下载管理器")
                    .setContentText("下载中...")
//                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_square))
                    .setSmallIcon(R.mipmap.ic_down_noti);//设置通知小ICON
        } else {
            mBuilder = new Notification.Builder(this)
                    .setContentTitle("下载管理器")//设置通知栏标题
                    .setContentText("下载中...") //设置通知栏显示内容
                    .setContentIntent(pendingIntent) //设置通知栏点击意图
                    .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
                    .setVibrate(new long[]{0})
                    .setSound(null)
//                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_square))
                    .setSmallIcon(R.mipmap.ic_down_noti);//设置通知小ICON
        }
//        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.LOLLIPOP){
//            mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
        // 关联PendingIntent
//            mBuilder.setFullScreenIntent(pendingIntent, false);// 横幅
//        }
        Notification notification = mBuilder.build();
        notification.flags = Notification.FLAG_NO_CLEAR;

        mId = 0x06;
        mNotificationManager.notify(mId, notification);
        //        startForeground(0x06, mNotification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    private long mCurrentTime;

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent == null) return;
        mCurrentTime = System.currentTimeMillis();
        String url = intent.getStringExtra(PARAM_APK_URL);
        String name = intent.getStringExtra(PARAM_APK_NAME);
        if (!StringUtils.isNull(name)) {
            mBuilder.setContentTitle(name);
            mNotificationManager.notify(mId, mBuilder.build());
        }
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        PRDownloader.download(url,
                Environment.getExternalStorageDirectory().getAbsolutePath()
                        .concat(File.separator)
                        .concat(Environment.DIRECTORY_DOWNLOADS),
                fileName)
                .build()
                .setOnStartOrResumeListener(() -> {
                    Toast.makeText(mContext, "下载开始", Toast.LENGTH_SHORT).show();
//                    sendBroadcast(new Intent(ACTION_DLE_START));
                    HRxBus.getInstance().post(HRxBus.RX_ACTION_INSTALL, ACTION_DLE_START);
                })
                .setOnPauseListener(() -> {
                })
                .setOnCancelListener(() -> mNotificationManager.cancel(0x06))
                .setOnProgressListener(progress -> {
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - mCurrentTime < 100) return;
                    mCurrentTime = currentTime;
                    final float progressPercent = Math.round(progress.currentBytes * 1000 / progress.totalBytes) / 10f;
                    DecimalFormat decimalFormat = new DecimalFormat("0.0");
                    int progress1 = (int) Float.parseFloat(decimalFormat.format(progressPercent));
                    mBuilder.setProgress(100, progress1, false)
                            .setContentText("下载中".concat(String.valueOf(progress1)).concat("%")); //设置通知栏显示内容
                    mNotificationManager.notify(mId, mBuilder.build());
                })
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        try {
                            mNotificationManager.cancel(mId);
//                            sendBroadcast(new Intent(ACTION_DLE_SUCCESS));
                            HRxBus.getInstance().post(HRxBus.RX_ACTION_INSTALL, ACTION_DLE_SUCCESS);
                            Toast.makeText(mContext, "下载完成", Toast.LENGTH_SHORT).show();
                            installFile(mContext, fileName);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Error error) {
                        Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                        mNotificationManager.cancel(mId);
                    }

                });
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static void installFile(Context context, String fileName) {
        File apkfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                .concat(File.separator)
                .concat(Environment.DIRECTORY_DOWNLOADS), fileName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName().concat(".fileprovider"), apkfile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
}
